package couk.mmtdigital.sm.control.commands
{
	import couk.mmtdigital.sm.ApplicationFacade;
	import couk.mmtdigital.sm.model.UserProxy;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	import org.puremvc.as3.interfaces.ICommand;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;

	public class CheckOutCommand extends SimpleCommand implements ICommand
	{
		private var downloadObj:Object;
		private var fileRO:RemoteObject
		
		override public function execute(notification:INotification):void{
			downloadObj = notification.getBody();
			var userProxy:UserProxy = facade.retrieveProxy(UserProxy.NAME) as UserProxy;
			var folderName:Array = downloadObj.folderName.split("/");
			
			fileRO = new RemoteObject("spreadsheetServices");
			fileRO.source = "sm.fileXML";
			fileRO.addEventListener(FaultEvent.FAULT, faultHandler);
			fileRO.updateCheckOut.addEventListener(ResultEvent.RESULT, resultHandler);
			fileRO.updateCheckOut(folderName[folderName.length-1], downloadObj.fileName, 0, userProxy.username);
			
		}
		
		//to catch fault connecting to the gateway
		private function faultHandler(fault:FaultEvent):void
        {
        	trace("code:\n" + fault.fault.faultCode + "\n\nMessage:\n" + fault.fault.faultString + "\n\nDetail:\n" + fault.fault.faultDetail);
        }
        
        private function resultHandler(evt:ResultEvent):void{
        	if(evt.result['valid'] == 1){
				sendNotification(ApplicationFacade.DOWNLOADFILE, downloadObj);
        	}
        }
	}
}